<template>
  <el-dialog
    :model-value="visible"
    :title="`演唱记录 - ${songName}`"
    :width="dialogWidth"
    @update:model-value="$emit('update:visible', $event)"
    @close="$emit('close')"
    align-center
  >
    <div
      v-if="visible"
      v-motion
      :initial="{ opacity: 0, y: 20 }"
      :enter="{ opacity: 1, y: 0, transition: { duration: 300 } }"
    >
      <div v-loading="loading" class="p-4 h-full" style="max-height: 60vh; overflow-y: auto;">
        <div v-if="!loading && records.length === 0" class="text-center text-gray-500">
          暂无演唱记录
        </div>
        <div v-else class="space-y-4">
          <div v-for="record in records" :key="record.id" class="border rounded-lg p-3 bg-gray-50">
            <p><strong>演唱日期:</strong> {{ record.performed_at }}</p>
            <p v-if="record.notes"><strong>备注:</strong> {{ record.notes }}</p>
            <a :href="record.url" target="_blank" rel="noopener noreferrer" class="text-blue-500 hover:underline">
              观看视频
            </a>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { Record } from '~/types/record'

const props = defineProps<{
  visible: boolean
  songId: number | null
  songName: string
}>()

defineEmits(['update:visible', 'close'])

const records = ref<Record[]>([])
const loading = ref(false)

const dialogWidth = computed(() => {
  if (typeof window !== 'undefined') {
    return window.innerWidth > 768 ? '50%' : '90%'
  }
  return '50%'
})

async function fetchRecords() {
  if (!props.songId) return

  loading.value = true
  records.value = []
  try {
    const data = await $fetch(`/api/songs/${props.songId}/records`)
    records.value = data
  } catch (error) {
    console.error('Failed to fetch records:', error)
  } finally {
    loading.value = false
  }
}

watch(() => props.songId, (newId) => {
  if (newId && props.visible) {
    fetchRecords()
  }
})

watch(() => props.visible, (isVisible) => {
  if (isVisible && props.songId) {
    fetchRecords()
  }
})
</script>